package 力扣日常刷题.木23一月.第09天309;

/**
 * @author 帅小伙
 * @date 2022/3/9
 * @description
 * 2147483647
 */
public class Demo30把字符串转换成整数 {



    public int strToInt(String str) {
        char[] c = str.trim().toCharArray();
        if(c.length == 0) return 0;
        // 设置边界
        int res = 0, boundry = Integer.MAX_VALUE / 10;
        int start = 1, sign = 1;
        if(c[0] == '-') sign = -1;
        else if(c[0] != '+') start = 0;
        for(int i = start; i < c.length; i++) {
            if(c[i] < '0' || c[i] > '9') break;
            if(res > boundry || res == boundry && c[i] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = res * 10 + (c[i] - '0');
        }
        return sign * res;
    }


}
